#include "StdAfx.h"
#include "XMLDocument.h"

namespace xercescHelpingLibrary
{

	CXMLDocument::CXMLDocument(void)
	{
		m_parser = NULL;
		m_errHandler = NULL;
		m_domDocument = NULL;
		m_rootElement = NULL;
	}

	CXMLDocument::~CXMLDocument(void)
	{
		if (m_rootElement)
		{
			delete m_rootElement;
			m_rootElement = NULL;
		}

		if (m_errHandler)
		{
			delete m_errHandler;
			m_errHandler = NULL;
		}

		// DON'T delete m_domDocument, the parser handles deleting documents when the parser gets deleted.

		if (m_parser)
		{
			delete m_parser;
			m_parser = NULL;
		}
	}

	//////////////////////////////////////////////////////////////////////////

	CXMLDocument* CXMLDocument::OpenDocument(string xmlFilePath, string xsdFilePath)
	{
		CXMLDocument* newObject = new CXMLDocument();
		newObject->m_parser = new XercesDOMParser();
		newObject->m_errHandler = (ErrorHandler*) new HandlerBase();
		newObject->m_parser->setErrorHandler(newObject->m_errHandler);

		try {
			newObject->m_parser->setValidationScheme(XercesDOMParser::Val_Always);
			newObject->m_parser->setDoNamespaces(true);
			newObject->m_parser->setDoSchema(true);
			newObject->m_parser->setExternalNoNamespaceSchemaLocation(xsdFilePath.c_str());
			newObject->m_parser->parse(xmlFilePath.c_str());
		}
		catch (const XMLException& toCatch) {
			char* message = XMLString::transcode(toCatch.getMessage());
			cout<< "Exception message is: \n"
				<< message << "\n";
			XMLString::release(&message);
			return NULL;
		}
		catch (const DOMException& toCatch) {
			char* message = XMLString::transcode(toCatch.msg);
			cout<< "Exception message is: \n"
				<< message << "\n";
			XMLString::release(&message);
			return NULL;
		}
		catch (...) {
			cout<< "Unexpected Exception \n" ;
			return NULL;
		}

		newObject->m_domDocument = newObject->m_parser->getDocument();
		newObject->m_rootElement = CXMLElement::CreateElement( newObject->m_domDocument->getDocumentElement() );

		return newObject;
	}

	//////////////////////////////////////////////////////////////////////////
	CXMLElement* CXMLDocument::GetRootElement()
	{
		return m_rootElement;
	}

	CXMLElement* CXMLDocument::getElementByAttribute(string attributeName, string attributeValue)
	{
		if (!m_rootElement) return NULL;
		return m_rootElement->getElementByAttribute(attributeName, attributeValue);
	}

}